package cn.tramy.pinxian.wind.handler.processor

import cn.tramy.pinxian.wind.handler.HandlerInfo
import org.slf4j.LoggerFactory
import org.springframework.core.annotation.AnnotationUtils

class DefaultAnnotationHandlerProcessor : AnnotationHandlerProcessor {
    override fun <T : Annotation> process(handlerObject: Any, annotationClazz: Class<T>): List<HandlerInfo<Any>> {
        val clazz = handlerObject.javaClass
        LOGGER.debug("process class {}", clazz.name)
        var handlerInfos: MutableList<HandlerInfo<Any>> = mutableListOf()

        clazz.declaredMethods.forEach {
            if (AnnotationUtils.findAnnotation(it, annotationClazz) != null && it.parameterCount >= 1) {
                val handler = AnnotationUtils.findAnnotation(it, annotationClazz)
                var async = false
                annotationClazz.declaredMethods.filter { it.name == "afterCommit" }.forEach { it.invoke(handler).also { if (it is Boolean) async = it } }
                val handlerInfo = HandlerInfo<Any>(handlerObject, it, it.parameterTypes[0] as Class<Any>, async)
                handlerInfos.add(handlerInfo)
            }
        }
        return handlerInfos
    }

    companion object {
        private val LOGGER = LoggerFactory.getLogger(DefaultAnnotationHandlerProcessor::class.java)
    }
}